package com.igrowing.springbootinit.manager;

import com.igrowing.springbootinit.common.ErrorCode;
import com.igrowing.springbootinit.exception.BusinessException;
import lombok.Data;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Description:    // 类说明
 *
 * @ClassName: RedisLimiterManager    // 类名，会自动填充
 * @Author: 周天赐        // 创建者
 * @Email: m18879004515@163.com
 * @Date: 2024/4/2 9:27   // 时间
 * @Version: 1.0     // 版本
 */
@Service
@Data
public class RedisLimiterManager {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 给每个用户分配一个限流器，key为接口名称+用户id
     * @param key
     */
    public void doRateLimit(String key)
    {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL,2,1, RateIntervalUnit.SECONDS);
        boolean result = rateLimiter.tryAcquire(1);
        if (!result)
        {
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST,"系统繁忙，请稍后再试");
        }
    }


}

    
    
